//封装axios的请求模块
import axios from "axios";
// 进度条组件
import NProgress from "nprogress";

axios.defaults.baseURL = "http://124.222.38.10:3000/";
// axios的拦截请求
axios.interceptors.request.use((req) => {
  NProgress.start();
  req.headers["token"] = getToken();
  return req;
});
function getToken() {
  let str = sessionStorage.getItem("user-login");
  if (!str) {
    return "";
  }
  return JSON.parse(str).token;
}
axios.interceptors.response.use((res) => {
  NProgress.done();
  return res;
});
let map = new Map([
  ["get", get],
  ["delete", del],
  ["post", post],
  ["put", put],
]);
function get(options) {
  return axios.get(options.url, { params: options.data });
}
function del(options) {
  return axios.delete(options.url, { params: options.data });
}
function post(options) {
  return axios.post(options.url, options.data);
}
function put(options) {
  return axios.put(options.url, options.data);
}

function request(options) {
  let mt = map.get(options.type);
  if (!mt) {
    return new Promise((resolve) => {
      resolve({ code: 403, data: null, msg: "没有次种请求方法" });
    });
  }
  return mt(options);
}
export default request;
